package com.beimin.evedata.hsqldb;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author jbeetstr
 *
 */
public class StringIterator implements Iterator<String> {
	private boolean eof;
	private String currentString;
	private final BufferedReader dataSource;
	private final char split;
	private final char ignore;

	public StringIterator(BufferedReader source, char split, char ignore) {
		this.dataSource = source;
		this.split = split;
		this.ignore = ignore;
		this.eof = false;
		findNext();
	}

	private void findNext() {
		try {
			StringBuilder currentSB;
			do {
				currentSB = new StringBuilder();
				eof = true;
				while (currentSB.length() == 0 || (currentSB.charAt(currentSB.length() - 1) != split)) {
					String nextLine = dataSource.readLine();
					if (nextLine == null)
						return;
					if (nextLine.length() > 0 && nextLine.charAt(0) != ignore)
						currentSB.append(' ').append(nextLine);
					eof = false;
				}
			} while (currentSB.length() <= 1);
			currentString = currentSB.substring(0, currentSB.length() - 1);
		} catch (IOException e) {
			eof = true;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		return !eof;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#next()
	 */
	public String next() {
		if (eof)
			throw new NoSuchElementException();
		String result = currentString;
		findNext();
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#remove()
	 */
	public void remove() {
		throw new UnsupportedOperationException();
	}
}